﻿using System;
using System.IO;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
//using MassTransit.Logging;

namespace HuntingFishGame.CustomerApi
{
    /// <summary>
    /// ActionFilter检测WebApi接口请求和响应 http://www.cnblogs.com/felixnet/p/5689501.html
    /// </summary>
    [AttributeUsageAttribute(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
    public class ApiActionAttribute : ActionFilterAttribute
    {
        private string _requestId;
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);
            _requestId = DateTime.Now.Ticks.ToString();

            //获取请求数据  
            Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result;
            string requestDataStr = "";
            if (stream != null && stream.Length > 0)
            {
                stream.Position = 0; //当你读取完之后必须把stream的读取位置设为开始
                using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
                {
                    requestDataStr = reader.ReadToEnd().ToString();
                }
            }

            //[POST_Request] {requestid} http://dev.localhost/messagr/api/message/send {data}
            //Logger.Instance.WriteLine("[{0}_Request] {1} {2}\r\n{3}", actionContext.Request.Method.Method, _requestId, actionContext.Request.RequestUri.AbsoluteUri, requestDataStr);
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            string responseDataStr = actionExecutedContext.Response.Content.ReadAsStringAsync().Result;
            //[POST_Response] {requestid} {data}
            //Logger.Instance.WriteLine("[{0}_Response] {1}\r\n{2}", actionExecutedContext.Response.RequestMessage.Method, _requestId, responseDataStr);
        }
    }
}